package io.p2p.stream.p2pmain.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.core.domain.udp.UdpApiHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class MainUdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        //获取DatagramPacket中的数据
        ByteBuf buf = packet.content();
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);

        // 将字节数组转换为JSON字符串
        String jsonData = new String(data, StandardCharsets.UTF_8);

        //log.info("Received JSON data: " + jsonData);

        try {
            JSONObject jsonObject = JSON.parseObject(jsonData);
            UdpApiHandler.process(ctx,packet.sender(),jsonObject);
        }catch(Exception e){
            log.error("UDP Handling exceptions: " + e.getMessage());
            exceptionCaught(ctx,e);
        }
    }
}
